﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sharp.WeShare.Common
{
    public class CacheHelper
    {
        /// <summary>
        /// 过期时间
        /// </summary>
        public DateTime ExpTime { get; set; }
        public string Value { get; set; }
        public string Key { get; set; }
        private static List<CacheHelper> list = new List<CacheHelper>();
        /// <summary>
        /// 根据key值获取value.此处已经加入了锁机制。
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetValue(string key)
        {
            var temp = list.FirstOrDefault(l => l.Key == key && l.ExpTime > DateTime.Now);
            if (temp != null)
            {
                return temp.Value;
            }
            //移除已过期的项
            list.RemoveAll(l => l.ExpTime <= DateTime.Now);
            return "";
        }
        /// <summary>
        /// 添加缓存项到缓存队列中。
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expTime">过期时间</param>
        public static void Add(string key, string value, DateTime expTime)
        {
            list.Add(new CacheHelper { Key = key, Value = value, ExpTime = expTime });
        }
        /// <summary>
        /// 刷新缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expTime">过期时间</param>
        public static void Refresh(string key, string value, DateTime expTime)
        {
            var temp = list.FirstOrDefault(l => l.Key == key);
            if (temp != null)//如果已存在，则刷新。如果未存在，则添加
            {
                temp.ExpTime = expTime;
                temp.Value = value;
            }
            else
            {
                Add(key, value, expTime);
            }
        }



    }
}
